package servlets.loginServlets;

import java.io.IOException;
import java.net.URL;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import managers.JsonManager;

import org.jsoup.Jsoup;

import structures.User;

public class NormalLoginServlet extends HttpServlet {
	private static final String URLBASE = "http://localhost:8080/ISellToYouRESTWebService/LoginByCredentials";
	private static final long serialVersionUID = 3453091955573157294L;
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response){
		String email, password, answer;
		
		URL url;
		JsonManager jsonManager;
		User user = null;
		jsonManager = new JsonManager();
		email = request.getParameter("email");
		password = request.getParameter("password");
		
		try {
			url = new URL(URLBASE + "?email=" + email + "&password=" + password);
			answer = Jsoup.connect(url.toString()).ignoreContentType(true).execute().body();
			
			
			if(answer.equals("null"))
				throw new Exception();
			
			
			user = jsonManager.toUser(answer);
			request.getSession().setAttribute("user", user);
			try {
				response.sendRedirect(request.getContextPath() + "/home.jsp");
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (Exception e1) {
			request.getSession().setAttribute("error", "yes");
			try {
				response.sendRedirect(request.getContextPath() + "/");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
}
